<template>
  <div class="app-container">
    <div class="head-container">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="产品名称" prop="productName">
          <el-input
            v-model="queryParams.productName"
            placeholder="请输入产品名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="产品编码" prop="productCode">
          <el-input
            v-model="queryParams.productCode"
            placeholder="请输入产品编码"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            size="small"
          >
            <el-option label="正常" value="0" />
            <el-option label="停用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>

      <div class="handle-container">
        <el-button
          v-hasPermi="['system:product:add']"
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
        >新增</el-button>
        <el-button
          v-hasPermi="['system:product:export']"
          icon="el-icon-download"
          size="small"
          @click="handleExport"
        >导出</el-button>
        <el-button
          type="primary"
          icon="el-icon-refresh"
          size="small"
          @click="toggleSearch"
        >
          {{ showSearch ? '收起' : '展开' }}
        </el-button>
      </div>
    </div>

    <el-table
      v-loading="loading"
      :data="productList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品ID" prop="productId" width="80" align="center" />
      <el-table-column label="产品名称" prop="productName" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="产品编码" prop="productCode" align="center" :show-overflow-tooltip="true" />
      <el-table-column label="状态" prop="status" align="center">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="'0'"
            :inactive-value="'1'"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="创建者" prop="createBy" align="center" />
      <el-table-column label="创建时间" prop="createTime" align="center" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:product:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['system:product:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row.productId)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" />
        </el-form-item>
        <el-form-item label="产品编码" prop="productCode">
          <el-input v-model="form.productCode" placeholder="请输入产品编码" />
        </el-form-item>
        <el-form-item label="产品描述" prop="productDesc">
          <el-input
            v-model="form.productDesc"
            type="textarea"
            placeholder="请输入产品描述"
            :rows="4"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio label="0">正常</el-radio>
            <el-radio label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, delProduct, addProduct, updateProduct, changeStatus } from '@/api/system/product';

export default {
  name: 'Product',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据产品表格数据
      productList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        productName: '',
        productCode: '',
        status: ''
      },
      // 表单参数
      form: {
        productId: null,
        productName: null,
        productCode: null,
        productDesc: null,
        status: '0'
      },
      // 表单校验
      rules: {
        productName: [
          { required: true, message: '产品名称不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '产品名称长度不能超过100个字符', trigger: 'blur' }
        ],
        productCode: [
          { required: true, message: '产品编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '产品编码长度不能超过50个字符', trigger: 'blur' }
        ],
        productDesc: [
          { max: 2000, message: '产品描述长度不能超过2000个字符', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询数据产品列表 */
    getList() {
      this.loading = true;
      listProduct(this.queryParams).then(res => {
        this.productList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加数据产品';
    },
    /** 修改按钮操作 */
    handleEdit(row) {
      this.reset();
      const productId = row.productId || this.ids
      getProduct(productId).then(res => {
        this.form = res.data;
        this.open = true;
        this.title = '修改数据产品';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.productId != null) {
            updateProduct(this.form).then(res => {
              if (res.code === 200) {
                this.msgSuccess('修改成功');
                this.open = false;
                this.getList();
              }
            });
          } else {
            addProduct(this.form).then(res => {
              if (res.code === 200) {
                this.msgSuccess('新增成功');
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 状态修改 */
    handleStatusChange(row) {
      const productId = row.productId;
      const status = row.status;
      this.$confirm('确认要修改该产品状态吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        changeStatus(productId, status).then(res => {
          if (res.code === 200) {
            this.msgSuccess('修改成功');
          }
        });
      }).catch(() => {
        row.status = status === '0' ? '1' : '0';
      });
    },
    /** 删除按钮操作 */
    handleDelete(productId) {
      const productIds = productId || this.ids;
      this.$confirm(
        `确认要删除选中的${productIds.length > 1 ? productIds.length : ''}条数据吗?`,
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(function() {
        return delProduct(productIds);
      }).then(res => {
        if (res.code === 200) {
          this.msgSuccess('删除成功');
          this.getList();
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.downloadFile('/system/product/export', queryParams, `product_${new Date().getTime()}.xlsx`);
    },
    /** 切换搜索条件 */
    toggleSearch() {
      this.showSearch = !this.showSearch;
    },
    /** 重置表单 */
    reset() {
      this.form = {
        productId: null,
        productName: null,
        productCode: null,
        productDesc: null,
        status: '0'
      };
      this.resetForm('form');
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.productId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    }
  }
};
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.head-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.handle-container {
  display: flex;
  gap: 10px;
}

.small-padding .el-button--mini {
  padding: 0;
}
</style>